from flask import Blueprint,request,jsonify
import json
from db import db1
from utils.acl import acl
from config import get_data
from utils.rs import rs
from utils.jwttoken import jwta
bp_user=Blueprint('bp_user',__name__)

@bp_user.route('/login',methods=['POST'])
def login():
    # username=request.form('username')
    # password=request.form('password')
    data=get_data()
    print(data,111)
    sql="select * from user where username='%s'"%(data['username'])
    res=db1.find(sql)
    password1=res['password']
    if password1==data['password']:
        # data1={"data":{'username':data['username']}}
        data1={'data':{'userid':res['id']}}

        token=jwta.jia_secret(data1)

        # 获取用户页面权限，接口权限
        pagelist=acl.get_page_relist(res['id'])
        interlist=acl.get_interface_relist(res['id'])
        print(interlist,"sdfghghdfgh")
        key='interface'+str(res['id'])
        rs.insertdata(key,*interlist)
        return jsonify({'code':200,'token':token,'userid':res['id'],'pagelist':pagelist,'username':res['username']})
    else:
        return jsonify({"code":404})

def getresdata(data):
    list=[]
    idlist={i["id"]: i for i in data if i["pid"] is None}
    for i in data:
        print(i["pid"])
        if i["pid"] is None:
            i["son"] = []
            list.append(i)
            continue
        if "son" not in idlist[i["pid"]]:
            idlist[i["pid"]]["son"] = []
        idlist[i["pid"]]["son"].append(i)
    return list




# li = [{'name': '组织用户', 'url': 'zhuzhi', 'id': 1, 'pid': None, 'pname': None},
#       {'name': '菜单权限', 'url': 'caidan', 'id': 2, 'pid': None, 'pname': None},
#       {'name': '组织管理', 'url': None, 'id': 8, 'pid': 1, 'pname': '组织用户'},
#       {'name': '用户管理', 'url': None, 'id': 9, 'pid': 1, 'pname': '组织用户'},
#       {'name': '职务管理', 'url': None, 'id': 10, 'pid': 1, 'pname': '组织用户'},
#       {'name': '岗位管理', 'url': None, 'id': 11, 'pid': 1, 'pname': '组织用户'}]
# getresdata(li)
#
# l = [{'name': '组织用户', 'url': 'zhuzhi', 'id': 1, 'pid': None, 'pname': None,
#       'son': [{'name': '组织管理', 'url': None, 'id': 8, 'pid': 1, 'pname': '组织用户'},
#               {'name': '用户管理', 'url': None, 'id': 9, 'pid': 1, 'pname': '组织用户'},
#               {'name': '职务管理', 'url': None, 'id': 10, 'pid': 1, 'pname': '组织用户'},
#               {'name': '岗位管理', 'url': None, 'id': 11, 'pid': 1, 'pname': '组织用户'}]},
#      {'name': '菜单权限', 'url': 'caidan', 'id': 2, 'pid': None, 'pname': None, 'son': []}]


@bp_user.route('/getresource')
def getresource():
    # uid=request.args.get('id')
    # uid=int(uid)
    uid=1
    res=acl.get_resourcelist(uid)
    print(res,111)
    mes=getresdata(res)
    print(mes,222)
    return jsonify({"list":mes,"code":200})

# 角色互斥表
@bp_user.route('/addjiaose',methods=['POST'])
def addjiaose():
    data1=get_data()
    roleid=data1['roleid']
    uid=data1['uid']
    sql="select roleide from mutual where roleid=%d"%(roleid)
    res=db1.find_all(sql)
    if res:
        print(res,111)
        sql1="select * from user_role where userid=%d and roleid=%d"%(int(uid),int(res[0]['roleide']))
        res=db1.find_all(sql1)
        print(res,222)
        if res:
            return jsonify({'mes':'不能添加'})
    sql = "select roleid from mutual where roleide=%i"%(roleid)
    ree = db1.find_all(sql)
    print(ree,333)
    if ree:
        sql3="select * from user_role where userid=%d and roleid=%d"%(int(uid),int(ree[0]['roleid']))
        req=db1.find_all(sql3)
        if req:
            return jsonify({'mes': '不能添加3'})
    else:
        # 查询去重
        sql4="select * from user_role where userid=%d and roleid=%d"%(uid,roleid)
        res0=db1.find(sql4)
        if res0:
            return jsonify({"mes":"已经有了，加不了了"})
        sql2="insert into user_role values(0,%d,%d)"%(int(uid),int(roleid))
        db1.update(sql2)
        print(666)
        return jsonify({'code':200})


@bp_user.route('/test1')
def test1():
    key='abac'
    rs.insert_hash(key,'ip','127.0.0.1')
    rs.insert_hash(key,'level','003')
    rs.insert_hash(key,'time',"['2021-10-10','2021-12-10']")
    values=rs.get_all_hash(key)
    print(values,1114444444444444444444444)
    for (k,v) in values.items():
        print(k,"asvbnm,nbfjhgf")
        if str(k,encoding='utf8')=='time':
            print(eval(v))
            print(eval(v)[0])
            print(eval(v)[1])
    return 'ok'


# 获取角色 和资源
@bp_user.route('/getjiaozhi')
def getjiaozhi():
    uid=1
    sql="select roleid from user_role where userid=%d"%(uid)
    res=db1.find_all(sql)
    print(res,666)
    if res:
        list1=[i['roleid'] for i in res]
        list2=[]
        for i in list1:
            sql1="select pid from role where id=%d"%(int(i))
            res1=db1.find(sql1)
            list2.append(res1['pid'])
            pid=max(list2)
            sql2="select id from role where pid=%d "%(int(pid))
            res3=db1.find(sql2)
            sql3="select resourceid from role_resource where roleid=%d"%(int(res3['id']))
            res4=db1.find_all(sql3)
            list3=[i['resourceid'] for i in res4]
            sql4="delete from user_resource where userid=%d"%(int(uid))
            db1.update(sql4)
            for i in list3:
                sql5="insert into user_resource values(0,%d,%d)"%(uid,int(i))
                db1.update(sql5)
            return 'ok666'
    return 'ok'

@bp_user.route('/getallrole')
def getallrole():
    sql="select * from role"
    res=db1.find_all(sql)
    return jsonify({"code":200,'list':res})


@bp_user.route('/getholiday')
def getholiday():
    sql="select * from holiday_type"
    res=db1.find_all(sql)
    return jsonify({'code':200,'list':res})

@bp_user.route('/getresourcedata')
def getresourcedata():
    #从redis取，如果有直接返回
    values=rs.get_str('dataresouce')
    print(values)
    if values:
        list=eval(values)
    else:
    # 如果没有查询
        sql="select * from data_source"
        res=db1.find_all(sql)
        list=[]
        if res:
            for i in res:
                dict={'id':i['id'],'name':i['name']}
                sql1="select id,name,type from %s"%(i['tablename'])
                subres=db1.find_all(sql1)
                dict['mes']=subres
                list.append(dict)
        # 存入redis
        rs.set_str('dataresouce',json.dumps(list))
    return jsonify({"code":200,'list':list})




















